package com.cg.controller;
import com.cg.Dto.LoginDto;
import com.cg.common.StringConstant;
import com.cg.result.R;
import com.cg.service.Impl.PersonnelServiceImpl;
import com.cg.service.PersonnelService;
import com.cg.util.JwtUtil;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.media.Schema;
import jakarta.annotation.Resource;
import jakarta.servlet.http.HttpServletRequest;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;
@RestController
public class Login {
    private static final Logger logger = LoggerFactory.getLogger( PersonnelServiceImpl.class);
    @Resource
    private PersonnelService personnelService;
    @Resource
    private JwtUtil jwtUtil;
    @Resource
    private RedisTemplate<String,Object> redisTemplate;
    @Schema(description = "登录接口")
    @PostMapping("/login")
    public R login (@RequestBody @Validated LoginDto loginDto)
    {
      return  personnelService.login(loginDto);
    }
    //根据当前登录账号获取用户详细信息,从缓存里面获取账号信息
    @GetMapping("/detail")
    @Operation(description = "获取当前登录用户详情")
    public R getAccount(HttpServletRequest request)
    {
        return  personnelService.getAccount(request);
    }
    @PostMapping("/logout")
    @Operation(description = "退出登录接口")
    public R loginout(HttpServletRequest request)
    {
        // 获取请求头中的 token
        String token = request.getHeader(StringConstant.AUTHORIZATION);
        if (token == null || token.isEmpty()) {
            return R.Failed(StringConstant.ACCOUNTISNULL);
        }
        try {
            // 验证 token 的有效性
            jwtUtil.verifyToken(token);
            // 将 token 加入到 Redis 黑名单中
            jwtUtil.addToBlacklist(token);
            return R.Success("成功登出");
        } catch (Exception e) {
            // 记录日志并返回错误信息
            logger.error("Failed to log out: {}", e.getMessage(), e);
            return R.Failed("登出失败，请稍后再试");
        }
    }
    }

